<template>
  <div class="income-analysis">
    <!-- 标题部分 -->
    <div class="header-section">
      <h1 class="main-title">Income Data Analysis</h1>
      <p class="sub-title">
        This dashboard shows some of the data about the product.
      </p>
    </div>

    <!-- 内容区域 -->
    <div class="content-section">
      <!-- 筛选部分 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm">
          <el-form-item>
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="to"
              start-placeholder="Start time"
              end-placeholder="End time"
              value-format="YYYY-MM-DD"
              style="width: 260px" />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filterForm.category"
              placeholder="select the product category"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in categories"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filterForm.city"
              placeholder="select a City"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in cities"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="handleFilter">
                <el-icon>
                  <Search />
                </el-icon>
                Filter
              </el-button>
              <el-button @click="resetFilter">
                <el-icon>
                  <Refresh />
                </el-icon>
                Reset
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- 上半部分 -->
      <div class="upper-section">
        <el-row :gutter="20">
          <!-- 左侧卡片 -->
          <el-col :span="6">
            <div class="kpi-wrapper">
              <div class="kpi-section">
                <div v-for="(kpi, index) in kpiData" :key="index">
                  <el-card class="kpi-card" shadow="hover">
                    <div class="kpi-title">{{ kpi.title }}</div>
                    <div class="kpi-value">{{ kpi.value }}</div>
                    <div class="kpi-trends">
                      <div class="trend-item">
                        <div class="trend-label">Week-on-Week</div>
                        <div :class="['trend-value', kpi.weekOnWeek > 0 ? 'up' : 'down']">
                          <el-icon>
                            <CaretTop v-if="kpi.weekOnWeek > 0" />
                            <CaretBottom v-else />
                          </el-icon>
                          {{ Math.abs(kpi.weekOnWeek) }}%
                        </div>
                      </div>
                      <div class="trend-item">
                        <div class="trend-label">Day-over-Day</div>
                        <div :class="['trend-value', kpi.dayOnDay > 0 ? 'up' : 'down']">
                          <el-icon>
                            <CaretTop v-if="kpi.dayOnDay > 0" />
                            <CaretBottom v-else />
                          </el-icon>
                          {{ Math.abs(kpi.dayOnDay) }}%
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </el-col>

          <!-- 右侧折线图 -->
          <el-col :span="9" v-for="(chart, index) in upperCharts" :key="index">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">
                {{ chart.title }}
                <el-icon
                  class="chart-type-switch"
                  @click="toggleIncomeChartType(index)"
                  :title="getNextIncomeChartTypeTitle(currentIncomeChartType[index])">
                  <component :is="getIncomeChartTypeIcon(currentIncomeChartType[index])" />
                </el-icon>
              </div>
              <ECharts :options="getIncomeChartOptions(currentIncomeChartType[index], chart.options)" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 下半部分 -->
      <div class="lower-section">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(chart, index) in lowerCharts" :key="index">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">{{ chart.title }}</div>
              <ECharts :options="chart.options" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { CaretTop, CaretBottom, Search, Refresh, TrendCharts, DataLine, Histogram } from '@element-plus/icons-vue'
import { getIncomeAnalysis, getFilterOptions } from '@/api'
import ECharts from '@/components/ECharts.vue'
import { ElMessage } from 'element-plus'

// 筛选表单数据
const filterForm = reactive({
  dateRange: [],
  category: '',
  city: ''
})

// 选项数据
const categories = ref([])
const cities = ref([])

// KPI 数据
const kpiData = ref([])

// 图表数据
const upperCharts = ref([])  // 添加图表数据的ref
const lowerCharts = ref([])  // 添加图表数据的ref

// 图表类型
const currentIncomeChartType = ref(['line', 'line']) // 初始图表类型为折线图

// 获取数据
const fetchData = async () => {
  try {
    const params = {
      dateRange: filterForm.dateRange,
      category: filterForm.category,
      city: filterForm.city
    }

    const data = await getIncomeAnalysis(params)

    // 更新KPI数据
    kpiData.value = [
      {
        title: 'Cumulative sales',
        value: `${data.kpiData.totalProfit.toLocaleString()}`,
        weekOnWeek: data.kpiData.profitWeekOnWeek,
        dayOnDay: data.kpiData.profitDayOnDay
      },
      {
        title: 'Monthly profit',
        value: `${data.kpiData.monthlyProfit.toLocaleString()}`,
        weekOnWeek: data.kpiData.monthlyProfitWeekOnWeek,
        dayOnDay: data.kpiData.monthlyProfitDayOnDay
      }
    ]

    // 更新上部图表数据
    upperCharts.value = [
      {
        title: 'Cumulative Sales and Profit',
        options: getAccumulatedChartOptions(data.chartData)
      },
      {
        title: 'Monthly Sales and Profit',
        options: getMonthlyChartOptions(data.chartData)
      }
    ]

    // 更新下部图表数据
    lowerCharts.value = [
      {
        title: 'Product Category Sales Volume',
        options: getCategoryChartOptions(data.chartData)
      },
      {
        title: 'Commodity with the highest average profit',
        options: getProfitChartOptions(data.chartData)
      },
      {
        title: 'Commodities with the highest average profit margin',
        options: getProfitRateChartOptions(data.chartData)
      }
    ]
  } catch (error) {
    console.error('Failed to fetch data:', error)
    ElMessage.error('Failed to fetch data')
  }
}

// 初始化
onMounted(async () => {
  try {
    // 获取筛选选项
    const data = await getFilterOptions()
    categories.value = data.categories
    cities.value = data.cities

    // 获取初始数据
    await fetchData()
  } catch (error) {
    console.error('Failed to initialize:', error)
    ElMessage.error('Failed to initialize')
  }
})

// 处理筛选
const handleFilter = () => {
  fetchData()
}

// 重置筛选
const resetFilter = () => {
  filterForm.dateRange = []
  filterForm.category = ''
  filterForm.city = ''
  fetchData()
}

// 图表配置方法
const getAccumulatedChartOptions = (data) => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Sales', 'Profit']
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: data.months
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'Sales',
      type: 'line',
      data: data.totalSales
    },
    {
      name: 'Profit',
      type: 'line',
      data: data.totalProfits
    }
  ]
})

const getMonthlyChartOptions = (data) => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Sales', 'Profit']
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: data.months
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'Sales',
      type: 'line',
      data: data.monthSales
    },
    {
      name: 'Profit',
      type: 'line',
      data: data.monthProfits
    }
  ]
})

const getCategoryChartOptions = (data) => ({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'value'
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  yAxis: {
    type: 'category',
    data: data.categories
  },
  series: [
    {
      type: 'bar',
      data: data.salesVolumes
    }
  ]
})

const getProfitChartOptions = (data) => ({
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    axisLabel: {
      formatter: value => {
        return value / 10000
      }
    }
  },
  yAxis: {
    type: 'category',
    data: data.products
  },
  series: [
    {
      type: 'bar',
      data: data.avgProfits
    }
  ]
})

const getProfitRateChartOptions = (data) => ({
  tooltip: {
    trigger: 'axis',
    formatter: '{b}: {c}%'
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value}'
    }
  },
  yAxis: {
    type: 'category',
    data: data.products
  },
  series: [
    {
      type: 'bar',
      data: data.profitRates.map(rate => (rate * 100).toFixed(1))
    }
  ]
})


// 获取下一个收入图表类型的提示文字
const getNextIncomeChartTypeTitle = (currentType) => {
  switch (currentType) {
    case 'line': return '切换为面积图'
    case 'area': return '切换为柱状图'
    case 'bar': return '切换为折线图'
    default: return '切换图表类型'
  }
}

// 获取当前收入图表类型的图标
const getIncomeChartTypeIcon = (type) => {
  switch (type) {
    case 'line': return DataLine
    case 'area': return Histogram
    case 'bar': return TrendCharts
    default: return DataLine
  }
}

// 切换收入图表类型
const toggleIncomeChartType = (index) => {
  const currentType = currentIncomeChartType.value[index]
  if (currentType === 'line') {
    currentIncomeChartType.value[index] = 'area'
  } else if (currentType === 'area') {
    currentIncomeChartType.value[index] = 'bar'
  } else {
    currentIncomeChartType.value[index] = 'line'
  }
}

// 获取收入图表选项
const getIncomeChartOptions = (type, options) => {
  const newOptions = { ...options }
  newOptions.series = options.series.map(series => ({
    ...series,
    type: type === 'area' ? 'line' : type,
    areaStyle: type === 'area' ? {
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 0,
          color: series.name === 'Sales' ? 'rgba(64, 158, 255, 0.6)' : 'rgba(103, 194, 58, 0.6)'
        }, {
          offset: 1,
          color: series.name === 'Sales' ? 'rgba(64, 158, 255, 0)' : 'rgba(103, 194, 58, 0)'
        }]
      }
    } : null
  }))
  return newOptions
}
</script>

<style scoped>
.income-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header-section {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.sub-title {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.content-section {
  padding: 24px;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: -6px;
  margin-bottom: 0;
}

.filter-section :deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

.filter-section :deep(.el-button) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.kpi-wrapper {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.kpi-section {
  margin-bottom: 0;
}

.kpi-section>div:not(:last-child) {
  margin-bottom: 16px;
}

.kpi-card {
  padding: 0 16px;
  background-color: #F8FAFC;
  border: 1px solid #E4E7ED;
  height: 160px;
}

.kpi-card:hover {
  background-color: #F2F6FC;
  border-color: #DCDFE6;
}

.kpi-title {
  color: #409EFF;
  font-size: 14px;
  padding-top: 16px;
  margin-bottom: 8px;
}

.kpi-value {
  font-size: 24px;
  margin-bottom: 16px;
}

.kpi-trends {
  padding-bottom: 8px;
  gap: 8px;
}

.trend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-label {
  width: 97px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.trend-value.up {
  color: #f56c6c;
}

.trend-value.down {
  color: #67c23a;
}

.upper-section,
.lower-section {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #303133;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 0;
}

.chart-type-switch {
  cursor: pointer;
  margin-left: 8px;
  color: #909399;
}

.chart-type-switch:hover {
  color: #409EFF;
}
</style>